<template>
  <div class="clear-cache-container">
    <div class="clear-cache-card">
      <!-- 页面标题 -->
      <div class="header">
        <h1 class="title">清理缓存</h1>
        <p class="subtitle">清理所有本地缓存数据并重新登录</p>
      </div>

      <!-- 缓存信息展示 -->
      <div class="cache-info">
        <div class="info-item">
          <span class="label">用户信息缓存:</span>
          <span class="value" :class="{ 'has-data': hasUserCache }">
            {{ hasUserCache ? '已缓存' : '无缓存' }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">主题设置缓存:</span>
          <span class="value" :class="{ 'has-data': hasThemeCache }">
            {{ hasThemeCache ? '已缓存' : '无缓存' }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">页面标签缓存:</span>
          <span class="value" :class="{ 'has-data': hasTabsCache }">
            {{ hasTabsCache ? '已缓存' : '无缓存' }}
          </span>
        </div>
        <div class="info-item">
          <span class="label">本地存储总量:</span>
          <span class="value">{{ storageSize }}</span>
        </div>
      </div>

      <!-- 清理按钮 -->
      <div class="action-section">
        <el-button 
          type="danger" 
          size="large" 
          :loading="isClearing"
          @click="handleClearCache"
          class="clear-btn"
        >
          <el-icon v-if="!isClearing">
            <Delete />
          </el-icon>
          {{ isClearing ? '正在清理...' : '清理所有缓存' }}
        </el-button>
        
        <p class="warning-text">
          <el-icon><Warning /></el-icon>
          注意：清理缓存后将自动跳转到登录页面，您需要重新登录
        </p>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Warning, ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useTabsStore } from '@/stores/tabs'
import { clearThemeState } from '@/utils/theme'
import { clearDynamicRoutes } from '@/utils/dynamicRoutes'

// 路由实例
const router = useRouter()

// 状态管理
const userStore = useUserStore()
const tabsStore = useTabsStore()

// 响应式数据
const isClearing = ref(false)

// 计算属性：检查各种缓存是否存在
const hasUserCache = computed(() => {
  return localStorage.getItem('employeeInfo') !== null
})

const hasThemeCache = computed(() => {
  return document.documentElement.getAttribute('data-theme') !== null
})

const hasTabsCache = computed(() => {
  return tabsStore.tabs.length > 0
})

// 计算本地存储大小
const storageSize = computed(() => {
  let total = 0
  for (let key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
      total += localStorage[key].length + key.length
    }
  }
  
  // 转换为可读格式
  if (total < 1024) {
    return `${total} B`
  } else if (total < 1024 * 1024) {
    return `${(total / 1024).toFixed(2)} KB`
  } else {
    return `${(total / (1024 * 1024)).toFixed(2)} MB`
  }
})

/**
 * 清理所有缓存
 */
const handleClearCache = async () => {
  try {
    // 确认对话框
    await ElMessageBox.confirm(
      '确定要清理所有缓存吗？清理后将自动跳转到登录页面。',
      '确认清理',
      {
        confirmButtonText: '确定清理',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    isClearing.value = true

    // 显示清理进度
    ElMessage.info('正在清理用户信息缓存...')
    
    // 1. 清理用户状态管理
    userStore.clearUserInfo()
    
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.info('正在清理主题设置...')
    
    // 2. 清理主题状态
    clearThemeState()
    
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.info('正在清理路由缓存...')
    
    // 3. 清理动态路由
    clearDynamicRoutes()
    
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.info('正在清理页面标签...')
    
    // 4. 清理标签页状态
    tabsStore.closeAllTabs()
    
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.info('正在清理本地存储...')
    
    // 5. 清理所有localStorage（用户状态管理已经调用了localStorage.clear()，这里是确保清理）
    localStorage.clear()
    
    // 6. 清理sessionStorage
    sessionStorage.clear()
    
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 清理完成提示
    ElMessage.success('缓存清理完成！即将跳转到登录页面...')
    
    // 延迟跳转到登录页
    setTimeout(() => {
      router.replace('/login')
    }, 1000)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理缓存失败:', error)
      ElMessage.error('清理缓存失败，请重试')
    }
  } finally {
    isClearing.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

// 页面标题设置
onMounted(() => {
  document.title = '清理缓存'
})
</script>

<style scoped>
.clear-cache-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.clear-cache-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  max-width: 500px;
  width: 100%;
  text-align: center;
}

.header {
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.subtitle {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.cache-info {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  text-align: left;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 500;
  color: #495057;
}

.value {
  color: #6c757d;
  font-weight: 500;
}

.value.has-data {
  color: #28a745;
}

.action-section {
  margin-bottom: 30px;
}

.clear-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
}

.warning-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #e67e22;
  font-size: var(--font-size-base);
  margin: 0;
}

.back-section {
  border-top: 1px solid #e9ecef;
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .clear-cache-container {
    padding: 10px;
  }
  
  .clear-cache-card {
    padding: 30px 20px;
  }
  
  .title {
    font-size: 24px;
  }
}
</style>
